<!-- 
  腾讯地图的简单封装
-->
<template >
  <div :id="randomId" class="container"></div>
</template>
 
<script>
export default {
  name: "tencentmap",
  props: {
    centerPoint: {
      type: Object,
      default() {
        return {
          latitude: 22.53332,
          longitude: 113.93041,
        };
      },
    },
    zoom: {
      type: Number,
      default: 12,
    },
    markerClick: {
      type: Function,
      default() {
        return function () {};
      },
    },
    mapClick: {
      type: Function,
      default() {
        return function () {};
      },
    },
    pointList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      markerLayer: null,
      randomId: "e-map" + Date.now() + Math.random(),
    };
  },
  methods: {
    initMap() {
      //定义地图中心点坐标
      var center = new TMap.LatLng(
        this.centerPoint.latitude,
        this.centerPoint.longitude
      );
      //定义map变量，调用 TMap.Map() 构造函数创建地图
      var map = new TMap.Map(document.getElementById(this.randomId), {
        center: center, //设置地图中心点坐标
        zoom: this.zoom, //设置地图缩放级别
        pitch: 0, //设置俯仰角
        // rotation: 45, //设置地图旋转角度
      });
      //初始化marker图层
      let geometries = [
        {
          id: "0", //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
          position: new TMap.LatLng(
            this.centerPoint.latitude,
            this.centerPoint.longitude
          ),
          properties: {
            item: null,
          },
        },
      ];
      this.pointList.forEach((item, index) => {
        if (item.longitude) {
          geometries.push({
            id: index + 1, //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
            position: new TMap.LatLng(item.latitude, item.longitude),
            styleId: "myStyle",
            properties: {
              item: item,
            },
          });
        }
      });
      // geometries.unshift();
      this.markerLayer = new TMap.MultiMarker({
        id: "marker-layer",
        map: map,
        geometries: geometries,
        styles: {
          //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
          myStyle: new TMap.MarkerStyle({
            width: 36, // 点标记样式宽度（像素）
            height: 36, // 点标记样式高度（像素）
            src: require("../assets/images/point.png"), //图片路径
            //焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
            anchor: { x: 16, y: 32 },
          }),
        },
      });

      //监听点击事件添加marker
      map.on("click", (evt) => {
        console.log(evt,'==========');
        this.mapClick(evt.latLng);
        this.markerLayer.updateGeometries([
          {
            id: "0", //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
            position: new TMap.LatLng(evt.latLng.lat, evt.latLng.lng),
            properties: {
              item: null,
            },
          },
        ]);
      });
      this.markerLayer.on("click", (evt) => {
        console.log(evt,'markerLayer==========');
        this.markerClick(evt.geometry.properties.item);
      })
      // console.log(TMap,'==========');
    },
    loadScript() {
      if (document.getElementById('scriptId')) {
        this.initMap();
      } else {
        var script = document.createElement("script");
        script.setAttribute("id","scriptId");
        script.type = "text/javascript";
        script.src =
          "https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77";
        script.onload = script.onreadystatechange = () => {
          if (
            !this.readyState ||
            this.readyState === "loaded" ||
            this.readyState === "complete"
          ) {
            this.initMap();
            script.onload = script.onreadystatechange = null;
          }
        };
        document.body.appendChild(script);
      }
    },
  },
  mounted() {
    this.loadScript();
  },
  watch: {
    pointList: {
      handler: function (newVal, oldVal) {
        let geometries = [
            {
              id: "0", //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
              position: new TMap.LatLng(
                this.centerPoint.latitude,
                this.centerPoint.longitude
              ),
              properties: {
                item: null,
              },
            },
          ];
          this.pointList.forEach((item, index) => {
            if (item.longitude) {
              geometries.push({
                id: index + 1, //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
                position: new TMap.LatLng(item.latitude, item.longitude),
                styleId: "myStyle",
                properties: {
                  item: item,
                },
              });
            }
          });
          if (this.markerLayer) {
            this.markerLayer.setGeometries(geometries)
          }
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>
<style>
.container {
  /*地图(容器)显示大小*/
  width: 100%;
  height: 100%;
}
.container canvas {
  height: 200px;
}
</style>